package com.menglei.dailytasks.m0713;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

public class MyBroadcastReceiver extends BroadcastReceiver {
    /**
     * 一旦从 onReceive() 返回代码，BroadcastReceiver 就不再活跃。
     * 接收器的宿主进程变得与在其中运行的其他应用组件一样重要。
     * 如果该进程仅托管清单声明的接收器（这对于用户从未与之互动或最近没有与之互动的应用很常见），
     * 则从 onReceive() 返回时，系统会将其进程视为低优先级进程，
     * 并可能会将其终止，以便将资源提供给其他更重要的进程使用。
     */
    private static final String TAG = "MyBroadcastReceiver:";

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onReceive(Context context, Intent intent) {
        StringBuilder sb = new StringBuilder();
        sb.append("Action:" + intent.getAction() + "\n");
        sb.append("URI:" + intent.toUri(Intent.URI_INTENT_SCHEME).toString() + "\n");
        String log = sb.toString();
        Log.d(TAG, log);
        doNotificationAction(context, intent.getAction());
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void doNotificationAction(Context context, String action) {
        switch (action) {
            case "com.example.broadcast.MY_NOTIFICATION":
                NotificationManager.addNotification(context, "10", "广播", "我是自定义广播");
                break;
            case "android.net.wifi.WIFI_STATE_CHANGED":
                NotificationManager.addNotification(context,"11","广播","我是监听wifi");
                break;
            case "android.intent.action.AIRPLANE_MODE":
                ContentResolver cr = context.getContentResolver();
                if (Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON).equals("0")) {
                    Toast.makeText(context, "关闭", Toast.LENGTH_SHORT).show();
                    NotificationManager.addNotification(context, "12", "广播", "关闭飞行模式");
                } else {
                    Toast.makeText(context, "打开", Toast.LENGTH_SHORT).show();
                    NotificationManager.addNotification(context, "12", "广播", "打开飞行模式");
                }
                break;
            case "android.bluetooth.adapter.action.STATE_CHANGED":
                NotificationManager.addNotification(context, "13", "广播", "我是监听蓝牙");
                break;
        }
    }
}
